import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_ringtone_player/flutter_ringtone_player.dart';
import 'package:huxiaodui/api/api.dart';
import 'package:huxiaodui/api/model/alarm_model.dart';
import 'package:huxiaodui/api/model/notice_model.dart';
import 'package:huxiaodui/api/model/result.dart';
import 'package:huxiaodui/background_run/bg_channel.dart';
import 'package:huxiaodui/background_run/mqtt.dart';
import 'package:huxiaodui/background_run/mqtt_send.dart';
import 'package:huxiaodui/store/set.dart';
import 'package:huxiaodui/store/store.dart';
import 'package:huxiaodui/utils/position.dart';
import 'package:huxiaodui/utils/tools/notification_tool.dart';

class MQTTTask {
  static late ServiceInstance service;
  static Future<void> init(ServiceInstance service) async {
    MQTTTask.service = service;
    await MQTT().connect();
    await clientSubscribe();

    service.on(BgChannelType.mqttReconnect).listen((event) async {
      await MQTT().connect();
      await clientSubscribe();
    });

    /* 前台-使用MQTT推送 */
    service
        .on(BgChannelType.mqttSend)
        .listen((Map<String, dynamic>? event) async {
      MQTTSend.service(event!["type"], event["data"]);
    });

    /* 前台-停止警报 */
    service
        .on(BgChannelType.stopAlarm)
        .listen((Map<String, dynamic>? event) async {
      FlutterRingtonePlayer().stop();
      FlutterLocalNotificationsPlugin().cancel(1001);
    });

    Timer.periodic(const Duration(seconds: 20), (timer) async {
      await MQTTSend.service("heart", "心跳");
    });
  }

  static Future<void> clientSubscribe() async {
    //检测是否有校验登录 所需的Auth
    String? auth = await Store.auth.get();
    if (auth == null) {
      return;
    }
    //订阅并监听消息
    MQTT().subscribe(
      id: 1,
      topic: MyTopic.getClient(auth),
      onMessage: (msg) async {
        Map<String, dynamic> data = jsonDecode(msg);
        var type = data["type"];

        //将消息推送到前台
        service.invoke("Push-$type", data);

        //需要后台操作的内容
        if (type == "Alarm") {
          var alarm = AlarmModel.fromJson(data['alarm']);

          if(data['ring'] != null && data['ring'] != ""){
            FlutterRingtonePlayer().stop();
            FlutterRingtonePlayer().play(
              fromAsset: "assets/audio/${data['ring']}",
              volume: 1,
            );
          }
          if(data["showNotification"]){
            NotificationTool().alarm(alarm);
          }
          PositionTask.start();
        } else if (type == "Notice") {
          NoticeModel notice = NoticeModel.fromJson(data["notice"]);
          NotificationTool().notice(title: notice.title, body: notice.body);
        } else if (type == "Logout") {
          await Store.auth.del();
          await Store.mobileApp.del();
          MQTT().connect();
        }else if(type == "Alarms"){
          PositionTask.alarms = AlarmModel.toList(data["alarms"]);
          if(PositionTask.alarms.isNotEmpty){
            PositionTask.start();
          }else{
            PositionTask.stop();
          }
        }
      },
    );
    MQTTSend.service("heart", "心跳");
    //重新订阅后 重新上传一次位置
    Map<String, dynamic>? data = await Store.position.get();
    if (data != null) {
      MQTTSend.service(
          "position",
          jsonEncode(
              {"latitude": data["latitude"], "longitude": data["longitude"]}));
    }
  }
}


class PositionTask {
  static late ServiceInstance service;
  static bool isStart = false;
  static List<AlarmModel> alarms = [];
  static Future<void> init(ServiceInstance service) async {
    PositionTask.service = service;

    Timer.periodic(const Duration(seconds: 10), (timer) {
      if(PositionTask.alarms.isNotEmpty){
        start();
      }else{
        stop();
      }
    });
  }


  static Future<void> start() async {
    if (isStart) return;
    isStart = true;
    log("启用定位");
    await Position().init(
      locationInterval: 60 * 1000,
      onEvent: (Map<String, Object> res) async {
        service.invoke("Position", res);
        Store.position.save(res);
        MQTTSend.service(
          "position",
          jsonEncode(
            {"latitude": res["latitude"], "longitude": res["longitude"]},
          ),
        );
      },
    );
  }

  static Future<void> stop() async {
    if (!isStart) return;
    log("停用定位");
    Position().destroy();
    isStart = false;
  }
}
